package com.bawei.module_mine.ui

import android.os.CountDownTimer
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route

import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router

import com.bawei.lib_mvi.base.BaseActivity

import com.bawei.module_mine.databinding.ActivityCodeBinding
import com.bawei.module_mine.model.GetPermissions
import com.blankj.utilcode.util.ToastUtils
import java.util.Random

@Route(path = Router.Ui.CODE_ACTIVITY)
class CodeActivity : BaseActivity() {

    private val binding by lazy {
        ActivityCodeBinding.inflate(layoutInflater)
    }

    override fun initView() {
        super.initView()
        val randomNumber = generateRandomNumber()
        binding.tvHelp.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.HELP_ACTIVITY).navigation()
        }
        val countDownTimer = object : CountDownTimer(60000,1000){
            override fun onTick(p0: Long) {
                binding.tvPhoneLoginTime.setText("${p0/1000}")
            }

            override fun onFinish() {
                binding.tvPhoneLoginTime.setText("重新获取")
            }
        }
        binding.tvPhoneLoginTime.setOnClickListener {
            ToastUtils.showLong("验证码：${randomNumber}")
            countDownTimer.start()
        }
        binding.btnCodeLogin.setOnClickListener {
            if (binding.etCodeLogin.text.toString().equals(randomNumber) && GetPermissions.hasAllPermissions(this)){
                ToastUtils.showLong("登录成功")
                ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
            }else if (!binding.etCodeLogin.text.toString().equals(randomNumber)){
                ToastUtils.showLong("无效验证码")
            }else{
                ARouter.getInstance().build(Router.Ui.PHONE_BOOK_ACTIVITY).navigation()
            }
        }
        binding.ivBack.setOnClickListener {
            finish()
            countDownTimer.cancel()
        }
    }

    private fun generateRandomNumber() :String{
        val random = Random()
        val number = StringBuilder()
        for (i in 0 until 6){
            number.append(random.nextInt(10))
        }
        return number.toString()
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

}